package com.ruoyi.framework.security.filter;

import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤多租户tenantId
 *
 * @author likun
 */
@Slf4j
@Component
public class TenantFilter extends OncePerRequestFilter {

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        //验证当header中tenant为空时不走此Filter
        String tenant = request.getHeader(SecurityUtils.TENANT_ID);
        return StringUtils.isEmpty(tenant);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String tenant = request.getHeader(SecurityUtils.TENANT_ID);
        try {
            SecurityUtils.setThreadTenantId(Long.valueOf(tenant));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            filterChain.doFilter(request, response);
            SecurityUtils.removeThreadTenantId();
        }
    }
}
